<template>
    <view class="authorize">
        <slot></slot>
        <button v-if="!(vuex_hadAuthorize && token)" class="bindBtn" open-type="getUserInfo" lang="zh_CN" @getuserinfo="wxGetUserInfo"></button>
    </view>
</template>

<script>
import { getTokenByWxEncryptedData } from '@/api/authorize.js';
export default {
    data() {
        return {
            token: ''
        };
    },
    computed: {},
    created() {
        this.token = this.$storage.getStorage(this.$config.tokenKey);
    },
    methods: {
        // 获取到用户授权信息
        wxGetUserInfo(e) {
            if (e.detail && e.detail.userInfo) {
                let _detail = e.detail;
                let _userInfo = e.detail.userInfo;
                this.$u.vuex('vuex_hadAuthorize', true);
                // 设置用户信息
                this.setUserInfo(_userInfo.nickName, _userInfo.avatarUrl);
                // 获取授权信息
                getTokenByWxEncryptedData({
                    encryptedData: _detail.encryptedData,
                    iv: _detail.iv,
                    key: this.vuex_sessionKey
                }).then(data => {
                    this.$storage.setStorage(this.$config.tokenKey, data.Token);
                    this.token = this.$storage.getStorage(this.$config.tokenKey);
                    this.$emit('authorizeSuccess');
                });
            }
        },
        // 设置用户信息
        setUserInfo(nickName, avatarUrl) {
            this.$u.vuex('vuex_nickName', nickName);
            this.$u.vuex('vuex_avatarUrl', avatarUrl);
        }
    }
};
</script>

<style lang="less" scoped>
.authorize {
    position: relative;
    left: 0;
    top: 0;
    .bindBtn {
        position: absolute;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        z-index: 10;
        background-color: transparent;
        border: none;
        outline: none;
        margin: 0;
        padding: 0;
        &::after {
            border: none;
        }
    }
}
</style>
